using System;
using MimeCloud.AssetManagement.Editor.AssetCreation;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MimeCloud.AssetManagement.Business;
using Microsoft.Windows.Controls.Ribbon;
using Microsoft.Win32;
using MimeCloud.AssetManagement.AssetRendering;
using MimeCloud.AssetManagement.DigitalLibrary.Dialogs;
using MimeCloud.AssetManagement.Business.Interface;
using MimeCloud.AssetManagement.Editor;
using MimeCloud.AssetManagement.Editor.Saving;
using MimeCloud.AssetManagement.ProviderServices;
using MimeCloud.AssetManagement.ProviderServices.Repository;

namespace MimeCloud.AssetManagement.DigitalLibrary
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : RibbonWindow, IAssetContainer
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void OpenByIdCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void OpenByIdCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            Dialogs.OpenAssetById opener = new OpenAssetById();
            opener.ParentAssetContainer = this;
            opener.Show();
        }

        private void NewAsset_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            OpenAsset(AssetManagerConfig.GetAssetWriterProvider().GetBlankAsset()); //new LocalAsset{AssetContentList = new List<IAssetContent>(),AssetMetaDataList = new List<IMetaData>()});
        }

        public List<IAsset> OpenAssets = new List<IAsset>();

        public void OpenAsset(IAsset childAsset)
        {
            if (GetMatchingOpenAsset(childAsset)!=null)
            {
                MessageBox.Show("Asset already open");
                return;
            }
            
            OpenAssets.Add(childAsset);
            if (usrOpenAssetList.ItemsSource == null)
            {
                usrOpenAssetList.Items.Clear();
                usrOpenAssetList.ItemsSource = OpenAssets;
            }
            else
                usrOpenAssetList.Items.Refresh();

            DigitalAsset assetViewer = new DigitalAsset();
            assetViewer.DisplayAsset(childAsset);
            ContentGrid.Children.Add(assetViewer);
            usrOpenAssetList.SelectedItem = childAsset;
        }

        public IAsset GetMatchingOpenAsset(IAsset toMatch)
        {
            IAsset found = null;
            foreach (var asset in OpenAssets)
            {
                if (asset.IsEqual(toMatch))
                {
                    found = asset;
                    break;
                }
            }
            return found;
        }

        /// <summary>
        /// Create a new image asset content command
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NewImageContent_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            //get current asset viewer
            DigitalAsset currentViewer=null;
            currentViewer = CurrentViewer;
            if (currentViewer==null)
            {
                MessageBox.Show("No active asset");
                return;
            }
            else
            {
                //open file
                OpenFileDialog dl = new OpenFileDialog();
                dl.Filter = "Supported Image Files (*.jpg,*.gif,*.png)|*.jpg";
                dl.Title = "Select an image";
                dl.Multiselect = false;
                if (dl.ShowDialog().Value)
                {
                    IAssetContent newContent=null;
                    try
                    {
                        newContent = AssetManagement.Editor.AssetCreation.Image.CreateContent(dl.FileName);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        return;
                    }
                    //add to asset
                    currentViewer.ChildAsset.AssetContentList.Add(newContent);
                    //redisplay
                    currentViewer.UpdateDisplay();
                }
            }
            usrOpenAssetList.Items.Refresh();
            
        }

        private void NewVideoContent_Executed(object sender, ExecutedRoutedEventArgs e)
        {
             //get current asset viewer
            DigitalAsset currentViewer=null;
            currentViewer = CurrentViewer;
            if (currentViewer == null)
            {
                MessageBox.Show("No active asset");
                return;
            }
            else
            {
                //open file
                OpenFileDialog dl = new OpenFileDialog();
                dl.Filter = "Supported Video Files (*.wmv,*.flv) | *.wmv;*.flv";
                dl.Title = "Select a video";
                dl.Multiselect = false;
                if (dl.ShowDialog().Value)
                {
                    //ask for type
                    AssetContentTypeList listSelector = new AssetContentTypeList();
                    listSelector.DataContext =
                        AppCommon.Current.AllAssetContentTypes.Where(p => p.ContentType == TypeOfContent.Video);
                    if (listSelector.ShowDialog().Value)
                    {
                        IAssetContentType selectedType = listSelector.ContentTypeList.SelectedItem as IAssetContentType;


                        IAssetContent newContent = null;
                        try
                        {
                            newContent = AssetManagement.Editor.AssetCreation.Video.CreateContent(dl.FileName,selectedType);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            return;
                        }
                        //add to asset
                        currentViewer.ChildAsset.AssetContentList.Add(newContent);
                        //redisplay
                        currentViewer.UpdateDisplay();
                    }
                }
            }
            usrOpenAssetList.Items.Refresh();
        }

        DigitalAsset CurrentViewer
        {
            get
            {
                DigitalAsset currentViewer = null;
                foreach (var child in ContentGrid.Children)
                {
                    if (child is DigitalAsset && (child as DigitalAsset).Visibility==System.Windows.Visibility.Visible)
                    {
                        currentViewer = child as DigitalAsset;
                        break;
                    }
                }
                return currentViewer;
            }
        }

       

        private void usrOpenAssetList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count>0)
            {
                if (e.AddedItems[0] is IAsset)
                {
                    DisplayThisOpenAsset(e.AddedItems[0] as IAsset,false);
                }
            }
        }

        private void DisplayThisOpenAsset(IAsset selectedAsset, bool selectInList)
        {
            DigitalAsset current = CurrentViewer;
            if (current != null)
            {
                //do nothing if selected same asset as viewing
                if (current.ChildAsset.IsEqual(selectedAsset))
                    return;
            }

            //hide all others, display this one
            foreach (var child in ContentGrid.Children)
            {
                if (child is DigitalAsset && (child as DigitalAsset).ChildAsset.IsEqual(selectedAsset))
                    (child as DigitalAsset).Visibility = System.Windows.Visibility.Visible;
                else if (child is DigitalAsset && (child as DigitalAsset).Visibility == System.Windows.Visibility.Visible)
                    (child as DigitalAsset).Visibility = System.Windows.Visibility.Collapsed;
            }
            //todo: implement selectInList
        }

        private void NewContentType_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            IAssetContentType newType = AssetManagerConfig.GetAssetWriterProvider().GetBlankAssetContentType();
            AssetContentTypeEditor edit = new AssetContentTypeEditor();
            edit.DataContext = newType;
            if (edit.ShowDialog()==true)
            {
                IAssetContentType editedType = edit.DataContext as IAssetContentType;
                if (newType!=null)
                {
                    AssetManagerConfig.GetAssetWriterProvider().SaveAssetContentType(newType);
                    AppCommon.Current.ReloadData();
                }
                MessageBox.Show(String.Concat((edit.DataContext as IAssetContentType).ID,": ",(edit.DataContext as IAssetContentType).Name));
            }
        }
        private void NewMimeType_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            IMimeType newType = AssetManagerConfig.GetAssetWriterProvider().GetBlankMimeType();
            MIMETypeEditor edit = new MIMETypeEditor();
            edit.DataContext = newType;
            if (edit.ShowDialog() == true)
            {
                IMimeType editedType = edit.DataContext as IMimeType;
                if (newType != null)
                {
                    AssetManagerConfig.GetAssetWriterProvider().SaveMimeType(editedType);
                    AppCommon.Current.ReloadData();
                }
                MessageBox.Show((edit.DataContext as IMimeType).Name);
            }
        }

        private void NewContentType_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void UploadCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (OpenAssets.Count > 0)
                e.CanExecute = true;
        }

        

        private void UploadCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            DisparateDataSaveManager saver = new DisparateDataSaveManager();
            AssetSaveArguments args = new AssetSaveArguments();
            args.AssetsToSave = OpenAssets;
            args.SaveAssetMetadata = true;

            AssetSaveResult result = saver.Save(args);
        }

        private void CloseSelectedAssetCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if ((usrOpenAssetList.SelectedItem as IAsset) != null)
                e.CanExecute = true;
        }

        private void CloseSelectedAssetCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            //remove contentgrid child

            for (int i = 0; i < ContentGrid.Children.Count; i++)
            {
                var child = ContentGrid.Children[i];
                if (child is DigitalAsset &&
                    (child as DigitalAsset).ChildAsset.IsEqual(usrOpenAssetList.SelectedItem as IAsset))
                {ContentGrid.Children.RemoveAt(i);
                    break;}
                
            }
            for (int i = 0; i < OpenAssets.Count; i++)
            {
                if ((usrOpenAssetList.SelectedItem as IAsset).
                 IsEqual(OpenAssets[i]))
                {
                    OpenAssets.RemoveAt(i);
                    usrOpenAssetList.Items.Refresh();
                    if (usrOpenAssetList.Items.Count >= i)
                        usrOpenAssetList.SelectedIndex = i-1;
                    else if (usrOpenAssetList.Items.Count > 0)
                        usrOpenAssetList.SelectedIndex = usrOpenAssetList.Items.Count - 1;
                }
            }
            
            //remove selected list
        }

        private void LatestCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void LatestCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            IList<IAsset> latest = AssetManagerConfig.GetAssetSearcherProvider().LatestAssets(20);
            Dialogs.LatestAssets win = new LatestAssets();
            win.DisplayAssets = latest;
            win.Show();
        }

        private void ViewDebug_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void ViewDebug_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            new DebugWindow().Show();
        }

        private void listAssetContentType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 0)
                return;
            RibbonComboBox master = sender as RibbonComboBox;
            IAssetContentType newType = (e.AddedItems[0] as RibbonComboBoxItem).Tag as IAssetContentType;
            AssetContentTypeEditor edit = new AssetContentTypeEditor();
            edit.DataContext = newType;
            if (edit.ShowDialog() == true)
            {
                IAssetContentType editedType = edit.DataContext as IAssetContentType;
                if (newType != null)
                {
                    AssetManagerConfig.GetAssetWriterProvider().SaveAssetContentType(newType);
                    AppCommon.Current.ReloadData();
                }
                MessageBox.Show(String.Concat((edit.DataContext as IAssetContentType).ID, ": ", (edit.DataContext as IAssetContentType).Name));
            }
        }

        private void RibbonGroup_Loaded(object sender, RoutedEventArgs e)
        {
            listAssetContentType.ItemsSource =
                AssetManagerConfig.GetAssetReaderProvider()
                .GetAllAssetContentType()
                .Select(ct => new RibbonComboBoxItem { Tag = ct,Content = ct.Name })
                .ToList();
        }
    }
}
